<template>
  <div>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css"
    />
    <div
      v-if="this.$route.query.id == userId"
      style="
        position: absolute;
        float: left;
        margin-left: 560px;
        margin-top: 10px;
      "
    >
      <el-button round size="medium"
        ><router-link to="home" style="text-decoration: none; color: black"
          >返回首页</router-link
        ></el-button
      >
    </div>
    <div
      v-else
      style="
        position: absolute;
        float: left;
        margin-left: 560px;
        margin-top: 10px;
      "
    >
      <el-button round size="medium"
        ><router-link to="home" style="text-decoration: none; color: black"
          >返回</router-link
        ></el-button
      >
    </div>
    <div
      style="
        position: absolute;
        float: left;
        margin-left: 680px;
        margin-top: 10px;
      "
    >
      <el-button
        type="info"
        v-if="this.$route.query.id == userId"
        round
        size="medium"
        @click="editVisible = true"
        >账号资料</el-button
      >
    </div>
    <div
      v-if="this.$route.query.id == userId"
      style="position: absolute; margin-left: 59%; margin-top: 10px"
    >
      <el-button type="primary" size="medium" round @click="show"
        >修改密码</el-button
      >
    </div>
    <div
      v-else
      style="
        position: absolute;
        float: left;
        margin-left: 1300px;
        margin-top: 10px;
      "
    >
      <el-button type="info" round size="medium">私信</el-button>
    </div>
    <div
      v-if="this.$route.query.id == userId"
      style="position: absolute; margin-left: 65.5%; margin-top: 10px"
    >
      <el-button type="warning" round size="medium" @click="logout"
        >退出登录</el-button
      >
    </div>
    <!--     <div
      v-else-if="followArray.indexOf(UserID) >= 0"
      style="
        position: absolute;
        float: left;
        margin-left: 1390px;
        margin-top: 10px;
      "
    >
      <el-button type="success" round size="medium" @click="follow"
        >已关注</el-button
      >
    </div> -->
    <div
      v-else
      style="
        position: absolute;
        float: left;
        margin-left: 1390px;
        margin-top: 10px;
      "
    >
      <el-button type="primary" round size="medium" @click="follow"
        >关注</el-button
      >
    </div>
    <div class="block">
      <el-upload
        v-if="this.$route.query.id == userId"
        :action="url"
        :headers="headers"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <el-avatar :size="70" :src="src"></el-avatar>
      </el-upload>
      <el-avatar v-else :size="70" :src="src"></el-avatar>
      <div>
        <strong
          ><font style="font-size: 22px">{{ userInfo.nickname }}</font></strong
        >
      </div>
      <div style="margin-top: 10px">{{ userInfo.introduction }}</div>
    </div>
    <div style="width: 100%; margin-top: 10px">
      <el-tabs stretch v-model="activeName" @tab-click="handleClick">
        <el-tab-pane style="margin-left: 13.5%" label="发布" name="发布"
          ><BlogDetail
        /></el-tab-pane>
        <el-tab-pane style="margin-left: 13.5%" label="收藏" name="收藏"
          ><BlogDetail
        /></el-tab-pane>
        <el-tab-pane style="margin-left: 13.5%" label="关注" name="关注"
          ><UserInfo
        /></el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog
      style="width: 800px; margin-left: 30%"
      title="修改密码"
      :visible.sync="dialogFormVisible4Edit"
    >
      <el-form :model="formData" :rules="rules" ref="from">
        <el-form-item label="原密码" prop="oldPwd">
          <el-input
            type="password"
            v-model="formData.oldPwd"
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input
            type="password"
            v-model="formData.newPwd"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPwd1">
          <el-input
            type="password"
            v-model="formData.newPwd1"
            placeholder="请输入确认密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible4Edit = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="账号资料"
      :visible.sync="editVisible"
      width="400px"
      center
    >
      <el-form
        :model="form"
        ref="formInfo"
        label-width="80px"
        :rules="formRules"
      >
        <el-form-item prop="nickname" label="昵称" size="mini">
          <el-input v-model="form.nickname" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="电子邮箱" size="mini">
          <el-input v-model="form.email" placeholder="电子邮箱"></el-input>
        </el-form-item>
        <el-form-item prop="introduction" label="简介" size="mini">
          <el-input
            v-model="form.introduction"
            type="textarea"
            placeholder="简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button size="mini" @click="editVisible = false">取消</el-button>
        <el-button size="mini" @click="editSave">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import bus from "@/eventBus.js";
import BlogDetail from "@/views/BlogDetail.vue";
import UserInfo from "@/components/UserInfo.vue";

export default {
  components: {
    BlogDetail,
    UserInfo,
  },
  data() {
    return {
      activeName: "",
      url:
        "http://localhost:8081/blog/user/pic/" +
        JSON.parse(sessionStorage.getItem("user")).id,
      src: "http://localhost:8081/blog",
      dialogFormVisible4Edit: false,
      editVisible: false,
      userInfo: {},
      flag: true,
      followArray: [8],
      UserID: 0,
      formData: {
        id: JSON.parse(sessionStorage.getItem("user")).id,
        oldPwd: "",
        newPwd: "",
        newPwd1: "",
      },
      form: {
        id: JSON.parse(sessionStorage.getItem("user")).id,
        nickname: JSON.parse(sessionStorage.getItem("user")).nickname,
        email: JSON.parse(sessionStorage.getItem("user")).email,
        introduction: JSON.parse(sessionStorage.getItem("user")).introduction,
      },
      rules: {
        oldPwd: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "长度在 2 到 30 个字符",
            trigger: "blur",
          },
        ],
        newPwd: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "长度在 2 到 30 个字符",
            trigger: "blur",
          },
        ],
        newPwd1: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          {
            min: 2,
            max: 30,
            message: "长度在 2 到 30 个字符",
            trigger: "blur",
          },
        ],
      },
      formRules: {
        nickname: { required: true, message: "请输入昵称", trigger: "blur" },
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的电子邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  computed: {
    userId() {
      return JSON.parse(sessionStorage.getItem("user")).id;
    },
    nickname() {
      var user = JSON.parse(sessionStorage.getItem("user"));
      return user.nickname;
    },
    introduction() {
      var user = JSON.parse(sessionStorage.getItem("user"));
      return user.introduction;
    },
    img() {
      var user = JSON.parse(sessionStorage.getItem("user"));
      return user.img;
    },
    headers() {
      return { Authorization: sessionStorage.getItem("tokenStr") };
    },
  },
  created() {
    this.getUserInfo();
    this.getFollow();
  },
  methods: {
    getUserInfo() {
      this.$get("user/info/" + this.$route.query.id).then((res) => {
        if (res) {
          this.userInfo = res;
          this.UserID = res.id;
          this.src = this.src + res.img;
        }
      });
    },
    getFollow() {
      this.$get(
        "follow/0/100?id=" + JSON.parse(sessionStorage.getItem("user")).id
      ).then((res) => {
        if (res.code == 200) {
          if (res.data.records != null) {
            for (var i = 0; i < res.data.records.length; i++) {
              this.followArray[i] = res.data.records[i].id;
            }
          }
        }
      });
    },
    follow(e) {
      let token = sessionStorage.getItem("tokenStr");
      if (token === null || token === "") {
        this.$message.warning("请先登录");
        return;
      }
      console.log(e);
      if (this.flag) {
        let param = {
          userId: JSON.parse(sessionStorage.getItem("user")).id,
          authorId: this.$route.query.id,
        };
        this.$post("follow", param).then((res) => {
          if (res.code == 200) {
            this.flag = false;
            e.target.className =
              "el-button el-button--success el-button--medium is-round";
            e.target.innerText = "已关注";
          }
        });
      } else {
        this.$delete(
          "follow/" +
            JSON.parse(sessionStorage.getItem("user")).id +
            "/" +
            this.$route.query.id
        ).then((res) => {
          if (res.code == 200) {
            this.flag = true;
            e.target.className =
              "el-button el-button--primary el-button--medium is-round";
            e.target.innerText = "关注";
          }
        });
      }
    },
    handleClick() {
      if (this.activeName == "发布") {
        this.$get("release/" + this.$route.query.id).then((res) => {
          if (res.code == 200) {
            bus.$emit("share", res.data);
          }
        });
      } else if (this.activeName == "收藏") {
        this.$get("collect/" + this.$route.query.id + "/0/100").then((res) => {
          if (res.code == 200) {
            bus.$emit("share", res.data);
          }
        });
      } else if (this.activeName == "关注") {
        this.$get("follow/0/100?id=" + this.$route.query.id).then((res) => {
          if (res.code == 200) {
            if (res.data != null) {
              bus.$emit("share", res.data.records);
            }
          }
        });
      }
    },
    show() {
      this.formData = {};
      this.dialogFormVisible4Edit = true;
    },
    handleEdit() {
      this.$refs["from"].validate((valid) => {
        if (valid) {
          if (this.formData.newPwd == this.formData.newPwd1) {
            let param = {
              id: JSON.parse(sessionStorage.getItem("user")).id,
              newPwd: this.formData.newPwd,
              oldPwd: this.formData.oldPwd,
            };
            this.$put("user/pwd", param).then((res) => {
              if (res.code == 200) {
                this.dialogFormVisible4Edit = false;
              }
            });
          } else {
            this.$message.error("两次密码输入不一致，请检查!");
          }
        } else {
          this.$message.error("数据校验失败，请检查!");
        }
      });
    },
    editSave() {
      this.$refs["formInfo"].validate((valid) => {
        if (valid) {
          this.$put("user", this.form).then((res) => {
            if (res.code == 200) {
              this.editVisible = false;
            }
          });
        } else {
          this.$message.error("数据校验失败，请检查!", "error");
        }
      });
    },
    logout() {
      this.$confirm("您确定要退出吗？", "提示", {
        type: "warning",
      }).then(() => {
        sessionStorage.removeItem("user");
        sessionStorage.removeItem("tokenStr");
        setTimeout(this.$router.replace("/home"), 2000);
        this.$message.success("注销成功");
      });
    },
    beforeAvatarUpload(file) {
      var testMsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (testMsg != "jpg" && testMsg != "jpeg" && testMsg != "png") {
        this.$message({
          message: "上传文件只能是jpg、jpeg、png格式",
          type: "error",
        });
        return false;
      }
      return true;
    },
    handleAvatarSuccess(res) {
      if (res.code == 200) {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
    },
  },
};
</script>

<style >
.el-tabs__nav-wrap .el-tabs__nav-scroll .el-tabs__nav {
  width: 100%;
  display: flex;
  justify-content: space-around;
}
</style>